#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""use snmp to get server info
@author : qiu
@license : Copyright@haohandata
@version : 1.1.3
@history : modified in 2016-07-05
"""
import subprocess
from configparser import ConfigParser
import os
import sys
import time
import tools

_SEPARATOR = " "
_OK = 0
_ERROR = 1
LOGGER_FILE = "snmp_perf.log"


def get_snmp_pwds():
    # 获取配置文件中的时间同步阈值
    config = ConfigParser()
    # 读取配置文件
    try:
        config_file = os.getenv("INSPECTOR_HOME") + "/conf/install.conf"
        config.read(config_file)
        # 时间同步默认安全阈值
        snmp_pwds = config.get("snmp", "password").split(_SEPARATOR)
    # 读取配置文件失败
    except IOError:
        sys.exit(1)
    return snmp_pwds


def get_snmp_info(ip, oid, timeout=5):
    logger = tools.get_logger(LOGGER_FILE)
    start_time = int(time.time())
    status, output = _ERROR, "PASSWORD EMPTY?"
    for snmp_pwd in get_snmp_pwds():
        command = "snmpwalk -t %d -v2c -c %s %s %s" % (timeout, snmp_pwd, ip, oid)
        result = subprocess.run(
            command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        status = result.returncode
        output = result.stdout.decode("utf-8")
        if status == _OK:
            return status, output
    finish_time = int(time.time())
    logger.info("{0}-{1}:{2}s".format(ip, oid, (finish_time - start_time)))
    return status, output
